<template>
  <div class="upload" :class="{'multiple': type==='file' && multiple}">
    <div class="image_wrap" :style="{height: imageHeight}" v-if="newValue && !multiple">
      <img :src="newValue" class="img">
      <div class="button_list_wrap">
        <span class="button-list">
          <i class="jyfont jy-preview icon_custom preview" @click="handlePreview"></i>
<!--          <a class="alt-icon">ALT</a>-->
          <i class="jyfont delete icon_custom delete" @click="handleRemove"></i>
        </span>
      </div>
    </div>

    <div class="upload_btn" :style="{height: imageHeight}" style="display: flex;align-items:center;justify-content: center" @click="handleOpen" v-show="(!newValue || multiple) && type === 'file'">
      <i class="el-icon-plus plus"></i>
      <span class="upload_btn_info" v-if="!multiple">{{title||attrs.title}}</span>
    </div>
    <el-button v-if="type === 'button'" type="primary" @click="handleOpen">{{title||attrs.title}}</el-button>
    <p v-if="attrs.desc" class="desc">{{ attrs.desc }}</p>
    <el-dialog title="插入图片" :visible.sync="isOpen" :append-to-body="true" @close="handleClose">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="本地上传" name="2" v-loading="loadingImage">
          <div class="image-container">
            <upload-file accept="image/jpeg,image/jpg,image/png,image/gif"
                         v-bind="attrs"
                         :fileType="['png', 'jpg', 'jpeg', 'gif']"
                         :isShowTip="true"
                         :lazy="true"
                         :multiple="multiple"
                         :size="120"
                         :responseFn="handleResponse"
                         :action="uploadPath"
                         title="图片"
                         v-model="localImage"
            ></upload-file>
            <div class="free__gallery">
              <template v-for="(item, index) in imageList">
                <div :key="item.id" style="position: relative">
                  <div style="height: 130px; width: 130px; position: relative;padding: 0 5px"
                       @click="selectItem(item, index)">
                    <img
                        class="center" v-lazy="item.url" data="product"
                        width="120" height="120" style="object-fit: contain">
                  </div>
                  <div class="img_mask" v-if="item.selected" @click="selectItem(item, index)">
                    <svg-icon class="icon" icon-class="checked"/>
                  </div>
                </div>
              </template>
            </div>
          </div>
          <el-pagination
              class="pagination"
              background
              @current-change="handleCurrentChange"
              :current-page="pageParams.page"
              layout="total, prev, pager, next, jumper"
              :page-size="pageParams.pageSize"
              :total="total">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="1"  v-loading="loadingImage">
          <div class="image-container">
            <div class="free__gallery">
              <template v-for="(item, index) in imageList">
                <div :key="index" style="position: relative">
                  <div style="height: 130px; width: 130px; position: relative;padding: 0 5px"
                       @click="selectItem(item, index)">
                    <img
                        class="center" :src="item.url" data="product"
                        width="120" height="120" style="object-fit: contain">
                  </div>
                  <div class="img_mask" v-if="item.selected">
                    <svg-icon class="icon" icon-class="checked"/>
                  </div>
                </div>
              </template>
            </div>
          </div>
          <el-pagination
              class="pagination"
              background
              @current-change="handleCurrentChange"
              :current-page="pageParams.page"
              layout="total, prev, pager, next, jumper"
              :page-size="pageParams.pageSize"
              :total="total">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="saveProductList" :disabled="disabledAdd">添加</el-button>
  </span>
    </el-dialog>
    <el-dialog title="预览" :visible.sync="isOpenPreview" :append-to-body="true">
      <img
          :src="newValue"
          class="gallery-image"
      >
    </el-dialog>
  </div>
</template>

<script>
import formMixin from 'vue-ele-form/lib/mixins/formMixin';
import uploadFile from '@/components/Upload/uploadFile';
import {getMaterialPage} from '@/api/material';
import {mapGetters} from 'vuex';

export default {
    name: 'ele-form-upload-plus-file', // name 属性必须填写, 在使用时, 需要和这里定义的 name 一致
    components: {uploadFile},
    mixins: [formMixin], // 必须引入mixin
    props: {
    // value 是传递过来的值
        value: {
            type: [String, Array],
            default: ''
        },
        title: {
            type: String,
            default: ''
        },
        // desc是此组件的描述, 结构为
        // { style: {}, class: {}, on: {}, attrs: {} }
        desc: {
            type: Object,
            default () {
                return {};
            }
        },
        multiple: {
            type: Boolean,
            default: false
        },
        imageHeight: {
            type: String,
            default: '117px'
        },
        type: {
            type: String,
            default: 'file'
        }
    },
    computed: {
        ...mapGetters(['siteList', 'addCardId', 'delCardId', 'projectData']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        uploadPath () {
            return process.env.VUE_APP_BASE_API + '/upload-file?siteId=' + this.siteId;
        }
    },
    data () {
        return {
            disabledAdd: false,
            loadingImage: false,
            total: 0,
            activeName: '2',
            imageList: [],
            selectPic: {},
            localImage: '',
            pageParams: {
                page: 1,
                pageSize: 20,
                type: 2
            },
            isOpenPreview: false,
            isOpen: false,
            // 用于v-model绑定, 因为 v-model无法绑定props值
            newValue: this.value
        };
    },
    mounted () {
        // this.getData();
        this.imageList.forEach((res) => {
            res.selected = false;
        });
    },
    methods: {
        asyncImgChecked (url) {
            return new Promise((resolve, reject) => {
                let img = new Image();
                img.src = url;
                img.onload = () => {
                    resolve({width: img.width, height: img.height});
                };
            });
        },
        async selectItem (item, index) {
            this.disabledAdd = true;
            if (this.multiple) {
                this.imageList[index].selected = !this.imageList[index].selected;
                this.disabledAdd = false;
            } else {
                this.imageList.forEach((res) => {
                    res.selected = false;
                });
                this.imageList[index].selected = true;
                this.asyncImgChecked(this.imageList[index].url).then(res => {
                    this.imageList[index] = Object.assign({...this.imageList[index], ...res});
                    this.selectPic = this.imageList[index];
                    this.disabledAdd = false;
                });
            }
        },
        handleClick (tab, event) {
            this.imageList = [];
            this.pageParams.page = 1;
            this.pageParams.type = tab.name;
            this.getData();
        },
        getData () {
            this.loadingImage = true;
            getMaterialPage({...this.pageParams, siteId: this.siteId}).then((res) => {
                const {records} = res;
                records.forEach((res) => {
                    res.selected = false;
                });
                this.imageList = records;
                this.total = res.totalElements;
                this.loadingImage = false;
            }).catch(() => {
                this.loadingImage = false;
            });
        },
        handleResponse (response, file, fileList) {
            this.pageParams.type = 2;
            this.getData();
        },
        handleOpen () {
            this.getData();
            this.isOpen = true;
        },
        handleRemove (val) {
            this.imageList.map((res) => { res.selected = false; });
            this.selectPic = {};
            this.$emit('input', '');
        },
        handlePreview () {
            this.isOpenPreview = true;
        },
        handleClose () {
            this.isOpen = false;
            this.$emit('close');
        },
        // 添加
        saveProductList () {
            if (this.multiple) {
                const multipleData = this.imageList.filter(res => res.selected);
                multipleData.forEach(s => {
                    s.src = s.url;
                });
                this.$emit('input', multipleData);
                this.isOpen = false;
            } else {
                if (Object.keys(this.selectPic).length) {
                    this.isOpen = false;
                    this.$emit('input', this.selectPic.url);
                    this.$emit('complete', this.selectPic);
                } else {
                    this.$message.error('请选择图片');
                }
            }
        },
        handleCurrentChange (val) {
            this.pageParams.page = val;
            this.getData();
        }
    }
};
</script>

<style scoped lang="scss">
.desc {
  color: #666666;
  font-size: 14px;
  line-height: 20px;
  font-weight: 400;
  text-transform: initial;
  word-wrap: break-word;
  word-break: break-word;
  margin-top: 10px;
  margin-bottom: 10px;
  display: block;
  clear: both;
}

.upload {
  width: 260px;
  &.multiple{
    width: 100px;
    height: 133px;
  }
  .upload_btn {
    width: 100%;
    height: 100%;
    cursor: pointer;
    border: 2px dashed #2e60f8;
    border-radius: 2px;
    background-color: #f8f9fb;
    display: inline-block;
    text-align: center;
    font-size: 20px;
    color: #2e60f8;

    .plus {
      color: #2e60f8;
      font-size: 20px;
    }

    .upload_btn_info {
      margin-left: 10px;
      font-size: 14px;
      vertical-align: 0.125rem;
    }
  }

  .image_wrap {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: #f6f7f9;

    .img {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      max-width: 100%;
      max-height: 100%;
      margin: auto;
    }

    .button_list_wrap {
      display: none;
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(55, 55, 55, 0.6);

      .button-list {
        display: inline-block;

        .preview {
          color: #ffffff;
          font-size: 16px;
          margin-right: 20px;
        }

        .alt-icon {
          color: #ffffff;
          font-size: 14px;
          font-weight: 600;
        }

        .delete {
          font-size: 16px;
          color: #ffffff;
          margin-left: 20px;
        }
      }
    }

    &:hover {
      .button_list_wrap {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.image-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .free__gallery {
    flex: 1;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 0 5px;

    .img_mask {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 124px;
      height: 124px;
      border: 2px solid #1F7DF8;
      background-color: rgba(0, 0, 0, 0.3);

      .icon {
        z-index: 10;
        position: absolute;
        width: 40px;
        height: 40px;
        top: 50%;
        left: 50%;
        margin-left: -20px;
        margin-top: -20px;
      }
    }
  }
}
.gallery-image{
  width: 100%;
  object-fit: cover;
}
.pagination{
  text-align: right;
}
</style>
